package com.wuwei.elearning.question.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wuwei.elearning.enumPackage.Constant;
import com.wuwei.elearning.question.domain.*;
import com.wuwei.elearning.question.mapper.SelfTestMapper;
import com.wuwei.elearning.question.mapper.SelfTestResultMapper;
import com.wuwei.elearning.question.mapper.SubjectMapper;
import com.wuwei.elearning.question.vo.EChartsBarVo;
import com.wuwei.elearning.question.vo.GetResultVo;
import com.wuwei.elearning.question.vo.PageVo;
import com.wuwei.elearning.utils.result.Result;
import com.wuwei.elearning.utils.token.TokenUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 自我测试结果表 前端控制器
 * </p>
 *
 * @author wuwei
 * @since 2024-04-10
 */
@RestController
@CrossOrigin
@RequestMapping("/elearning/selfTestResult")
public class SelfTestResultController {

    @Resource
    private SelfTestMapper selfTestMapper;

    @Resource
    private SelfTestResultMapper selfTestResultMapper;
    @Autowired
    private SubjectMapper subjectMapper;

    /**
     * 分页获取self_test_result的方法
     * 1.先去self_test表根据selectedId获取相应的id
     * 2.再去self_test_result表根据self_test_id获取数据
     * @param selectedId 如果小于10000，则为chapter表中的id字段，如果大于10000，则为subject表的id加上10000
     * @return
     */
    @GetMapping("getList/{selectedId}/{currentPage}/{pageSize}")
    public Result<List<SelfTestResult>> getList(@PathVariable("selectedId") Long selectedId, @PathVariable("currentPage") Integer currentPage,
                                                @PathVariable("pageSize") Integer pageSize,HttpServletRequest request,
                                                @RequestParam("startTime") String startTime,@RequestParam("endTime") String endTime){
        //获取用户名
        String token = request.getHeader("Authorization");
        Long account = TokenUtil.getAccountFromToken(token);
        LocalDateTime startOfDay = null;
        if (!startTime.equals("")) {
            startOfDay = LocalDate.parse(startTime).atStartOfDay();
        }
        LocalDateTime endOfDay = null;
        if (!endTime.equals("")) {
            // 如果要查询到这一天的最后一刻，应该设置为23:59:59
            endOfDay = LocalDate.parse(endTime).atTime(23, 59, 59);
        }
        System.out.println(endOfDay);
        Integer skipPages = (currentPage-1)*pageSize;
        List<SelfTestResult> records = selfTestResultMapper.myConditionQuery(selectedId,account,startOfDay,endOfDay,pageSize,skipPages);
        return Result.ok(records);
    }

    /**
     * 统计各根科目的自测平均成绩
     * @param request
     * @return
     */
    @GetMapping("statistics/all")
    public Result<EChartsBarVo> statisticsAll(HttpServletRequest request){
        //获取用户名
        String token = request.getHeader("Authorization");
        Long account = TokenUtil.getAccountFromToken(token);
        List<Long> rootSubjectIds = Arrays.asList(Constant.SUBJECTIDS);
        EChartsBarVo eChartsBarVo = extracted(rootSubjectIds, account);
        return Result.ok(eChartsBarVo);
    }

    /**
     * 按照科目统计各子科目的自测平均成绩
     * @param request
     * @return
     */
    @GetMapping("statisticsBySubject/{subjectId}")
    public Result<EChartsBarVo> statisticsBySubject(HttpServletRequest request,@PathVariable("subjectId") Long subjectId){
        //获取用户名
        String token = request.getHeader("Authorization");
        Long account = TokenUtil.getAccountFromToken(token);
        List<Long> rootSubjectIds = subjectMapper.getLeafsIdByParentId(subjectId);
        EChartsBarVo eChartsBarVo = extracted(rootSubjectIds, account);
        return Result.ok(eChartsBarVo);
    }

    private EChartsBarVo extracted(List<Long> rootSubjectIds, Long account) {
        EChartsBarVo eChartsBarVo = new EChartsBarVo();
        for (Long rootSubjectId : rootSubjectIds) {
            Subject subject = subjectMapper.selectById(rootSubjectId);
            List<Long> sonsById = subjectMapper.getSonsById(rootSubjectId);
            List<Long> selfTestIds;
            Integer score = 0;
            Integer count = 0;
            if (!sonsById.isEmpty()) {
                selfTestIds = selfTestMapper.selectList(new LambdaQueryWrapper<SelfTest>()
                        .eq(SelfTest::getCreateBy, account)
                        .in(SelfTest::getSelectedId, sonsById))
                        .stream().map(SelfTest::getId).collect(Collectors.toList());
                if (!selfTestIds.isEmpty()) {
                    List<SelfTestResult> selfTestResults = selfTestResultMapper.selectList(new LambdaQueryWrapper<SelfTestResult>()
                            .in(SelfTestResult::getSelfTestId, selfTestIds));
                    for (SelfTestResult selfTestResult : selfTestResults) {
                        score+=selfTestResult.getScore();
                        count++;
                    }
                }
            }
            if (count!=0) {
                double average = (double)score/count;
                String str = String.format("%.2f", average);
                eChartsBarVo.getData().add(count.toString());
                eChartsBarVo.getData2().add(str);
                eChartsBarVo.getIds().add(rootSubjectId);
                eChartsBarVo.getXAxis().add(subject.getName());
            }
        }
        return eChartsBarVo;
    }


    @GetMapping("getTotal/{selectedId}")
    public Result<Long> getTotal(@PathVariable("selectedId") Long selectedId,HttpServletRequest request
            , @RequestParam("startTime") String startTime,@RequestParam("endTime") String endTime){
        //获取用户名
        String token = request.getHeader("Authorization");
        Long account = TokenUtil.getAccountFromToken(token);
        LocalDateTime startOfDay = null;
        if (!startTime.equals("")) {
            startOfDay = LocalDate.parse(startTime).atStartOfDay();
        }
        LocalDateTime endOfDay = null;
        if (!endTime.equals("")) {
            // 如果要查询到这一天的最后一刻，应该设置为23:59:59
            endOfDay = LocalDate.parse(endTime).atTime(23, 59, 59);
        }
        Long count = selfTestResultMapper.myConditionCountQuery(selectedId,account,startOfDay,endOfDay);
        return Result.ok(count);
    }

}

